package cn.edu.zjut.mina.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;

import cn.edu.zjut.mina.po.User;
import cn.edu.zjut.mina.repository.UserRepository;
import cn.edu.zjut.mina.service.IMyService;
import cn.edu.zjut.mina.util.SessionMap;

@Service("myService")
public class MyServiceImpl implements IMyService {
	
	@Autowired
	private UserRepository userRepository;

	@Transactional(rollbackFor=Exception.class)
	public void MethodOne(final String key) {
		// TODO Auto-generated method stub
		System.out.println(".....");
		User user = new User();
		user.setUname("111");
		user.setPassword("222");
		userRepository.saveAndFlush(user);
		SessionMap sessionMap = SessionMap.newInstance();
		String[] keys = {key};
		System.out.println("=========================================================================");
		for (int i = 0; i < keys.length; i++) {
			System.out.println(keys[i]);
		}
		System.out.println("=========================================================================");
		sessionMap.sendMessage(keys, JSON.toJSONString(user));
		Sort sort = new Sort(Direction.DESC, "autoid");
		Pageable pageable = new PageRequest(1, 15);
		userRepository.findAll(sort);
		Page<User> page = userRepository.findAll(pageable);
		
		
		
		final User condition = new User();
		
		Page<User> page2 = userRepository.findAll(new Specification<User>() {  
			public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				 List<Predicate> list = new ArrayList<Predicate>();  
	                list.add(cb.equal(root.get("autoid").as(Integer.class), condition.getAutoid()));  
	                if (condition.getUname() != null) {  
	                    list.add(cb.equal(root.get("id").as(String.class), condition.getUname()));  
	                }  
	                if (condition.getIp()!=null) {  
	                    list.add(cb.like(root.get("ip").as(String.class), "%" + condition.getIp() + "%"));  
	                }  
	                Predicate[] predicates = new Predicate[list.size()];  
	                predicates = list.toArray(predicates);  
	                return cb.and(predicates);  
			}  
        }, pageable);  
	}
	
	

}
